package leetcode.dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: https://leetcode.cn/problems/permutations/
 * @Author Ammar
 * @Create 2023/7/19 15:02
 */
public class _46_全排列 {

    private List<List<Integer>> list;

    private int[] nums;

    private int[] result;

    private boolean[] used;

    public List<List<Integer>> permute(int[] nums) {
        if (nums == null) return null;
        list = new ArrayList<>();
        if (nums.length == 0) return list;
        this.nums = nums;

        result = new int[nums.length];
        used = new boolean[nums.length];
        dfs(0);
        return list;
    }

    private void dfs(int idx) {
        if (idx == nums.length) { // 最深层
            List<Integer> resultList = new ArrayList<>();
            for (int value : result) {
                resultList.add(value);
            }
            list.add(resultList);
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            result[idx] = nums[i];
            used[i] = true;
            dfs(idx + 1);
            used[i] = false;
        }
    }

    public List<List<Integer>> permute1(int[] nums) {
        if (nums == null) return null;
        List<List<Integer>> list = new ArrayList<>();
        if (nums.length == 0) return list;
        dfs1(0, nums, list);
        return list;
    }

    private void dfs1(int idx, int[] nums, List<List<Integer>> list) {
        if (idx == nums.length) { // 最深层
            List<Integer> resultList = new ArrayList<>();
            for (int value : nums) {
                resultList.add(value);
            }
            list.add(resultList);
            return;
        }

        for (int i = idx; i < nums.length; i++) {
            swap(nums, i, idx);
            dfs1(idx + 1, nums, list);
            swap(nums, i, idx);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
